# coding=utf-8
import json
import os
import threading
import time
import traceback

from PyQt5 import QtCore
# pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pyqt5-tools -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install PyQtWebEngine -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pynput -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install time -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install yaml -i https://pypi.tuna.tsinghua.edu.cn/simple
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QTableWidget, QMenu, QTableWidgetItem

from common.tools import get_project_path
from logs.log import get_log
from ui.BaseWin import BaseWin

log = get_log("RecordUi")


class RecordUi(BaseWin):
    switch_win = QtCore.pyqtSignal(object)

    def __init__(self, app, config):
        super(RecordUi, self).__init__(app)
        # self.setWindowTitle("我是子窗口啊")
        self.config = config
        self.init_ui()
        # self.setWindowFlag(QtCore.Qt.WindowType.WindowStaysOnTopHint, True)

    def create_table(self):
        self.table = QTableWidget()
        self.table.setRowCount(0)
        self.table.setColumnCount(6)
        self.table.verticalHeader().setVisible(False)  # 去掉行号
        self.table.resizeColumnsToContents()  # 设置表格自动列宽
        header = self.table.horizontalHeader()
        header.setStyleSheet(
            "QHeaderView::section {background-color: rgb(26, 182, 255); color: white;} ")  # 设置表头颜色为红色，字体颜色为白色
        self.table.setShowGrid(True)

        self.table.setHorizontalHeaderLabels(['执行时间', '耗时', '结果', '成功', '失败', '错误'])

        self.table.setColumnWidth(0, 150)
        self.table.setColumnWidth(1, 100)
        self.table.setColumnWidth(2, 100)
        self.table.setColumnWidth(3, 100)
        self.table.setColumnWidth(4, 100)
        self.table.setColumnWidth(5, 400)

        self.table.cellChanged.connect(self.printTable)
        # self.table.cellDoubleClicked.connect(self.del_func)
        self.table.setAlternatingRowColors(True)  # 隔行变色设置

        # 打开 右键菜单 设置
        self.table.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)  # 允许右键产生子菜单
        self.table.customContextMenuRequested.connect(self.sonsTableGenerateMenu)  # 联接右键菜单

        return self.table

    def sonsTableGenerateMenu(self, pos):
        # print( pos)
        menu = QMenu()
        item1 = menu.addAction(u"添加行")
        item2 = menu.addAction(u"删除行")
        action = menu.exec_(self.table.mapToGlobal(pos))  # 窗口坐标系转换为屏幕坐标系
        if action == item1:
            self.add_func()
        elif action == item2:
            self.del_func()
        else:
            pass

    def printTable(self):
        log.info("printTable")

    def init_ui(self):
        self.setWindowTitle("执行记录")
        # 创建布局
        layout = QVBoxLayout()
        print("22")
        # 创建QListWidget组件

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.create_table())

        layout.addLayout(hbox2)
        # 将网格布局应用到当前窗口
        self.setLayout(layout)
        self.set_center()
        print("11")
        self.init_data()

    def init_data(self):
        def load_data():
            dir_path = get_project_path() + ('/'.join(["temp", "result"]))
            file_list = os.listdir(dir_path)
            row = self.table.rowCount()
            rows = []
            for file in file_list:
                print(file)
                with open(os.path.join('/'.join([dir_path, file]), "data.json"), 'r') as f:
                    content = f.read()
                    try:
                        data = json.loads(content)
                        if data['config']['module'] == self.config['module'] and data['config']['method'] == \
                                self.config['method']:
                            total_time = f"{round(float(data['use_time']))}秒"
                            time_array = time.strptime(file, "%Y%m%d%H%M%S")
                            start_time = time.strftime("%Y/%m/%d %H:%M:%S", time_array)
                            success = '成功' if bool(data['success']) == True else '失败'
                            success_list = list(filter(lambda x: x['success'] and x['success'] == True, data['list']))
                            success_count = 0 if success != '成功' else len(success_list)
                            fail_count = len(data['list']) if success != '成功' else (
                                    len(data['list']) - len(success_list))
                            error = data['error'] if data['error'] else ''
                            rows.append((start_time, total_time, success, success_count, fail_count, error, file))
                            log.info(f"{start_time}-{total_time}-{success}")
                    except BaseException as e:
                        log.error(traceback.format_exc())
                        log.error(str(e))

            self.table.setRowCount(len(rows))
            for g in rows:
                item1 = QTableWidgetItem()
                item1.setText(str(g[0]))
                item1.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                item2 = QTableWidgetItem()
                item2.setText(str(g[1]))
                item2.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                item3 = QTableWidgetItem()
                item3.setText(str(g[2]))
                item3.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                item4 = QTableWidgetItem()
                item4.setText(str(g[3]))
                item4.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                item5 = QTableWidgetItem()
                item5.setText(str(g[4]))
                item5.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                item6 = QTableWidgetItem()
                item6.setText(str(g[5]))
                item6.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
                self.table.setItem(row, 0, item1)
                self.table.setItem(row, 1, item2)
                self.table.setItem(row, 2, item3)
                self.table.setItem(row, 3, item4)
                self.table.setItem(row, 4, item5)
                self.table.setItem(row, 5, item6)
                row = row + 1

        thread = threading.Thread(target=load_data)
        thread.start()

    def closeEvent(self, event):
        self.switch_win.emit(self.config)
        pass
